using Infrastructure.Attribute;
using Infrastructure.Extensions;
using JTZY.Model.Order.Dto;
using JTZY.Model.Order;
using JTZY.Repository;
using JTZY.Service.Order.IOrderService;
using Infrastructure;
using Infrastructure.Enums;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json.Linq;
using static JTZY.Common.GlobalEnumVars;
using JTZY.Common;

namespace JTZY.Service.Order
{
    /// <summary>
    /// 发货单表Service业务层处理
    /// </summary>
    [AppService(ServiceType = typeof(ICorecmsbilldeliveryService), ServiceLifetime = LifeTime.Transient)]
    public class CorecmsbilldeliveryService : BaseService<Corecmsbilldelivery>, ICorecmsbilldeliveryService
    {
        private readonly IServiceProvider _serviceProvider;

        public  CorecmsbilldeliveryService(IServiceProvider serviceProvider)
        {
            _serviceProvider = serviceProvider;
        }


        /// <summary>
        /// 查询发货单表列表
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        public PagedInfo<CorecmsbilldeliveryDto> GetList(CorecmsbilldeliveryQueryDto parm)
        {
            var predicate = QueryExp(parm);

            var response = Queryable()
                //.Includes(x => x.CorecmsbilldeliveryitemNav) //填充子对象
                .Where(predicate.ToExpression())
                .ToPage<Corecmsbilldelivery, CorecmsbilldeliveryDto>(parm);

            return response;
        }


        /// <summary>
        /// 获取详情
        /// </summary>
        /// <param name="DeliveryId"></param>
        /// <returns></returns>
        public Corecmsbilldelivery GetInfo(string DeliveryId)
        {
            var response = Queryable()
                .Includes(x => x.CorecmsbilldeliveryitemNav) //填充子对象
                .Where(x => x.DeliveryId == DeliveryId)
                .First();

            return response;
        }

        /// <summary>
        /// 添加发货单表
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public Corecmsbilldelivery AddCorecmsbilldelivery(Corecmsbilldelivery model)
        {
            return Context.InsertNav(model).Include(s1 => s1.CorecmsbilldeliveryitemNav).ExecuteReturnEntity();
        }

        /// <summary>
        /// 修改发货单表
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int UpdateCorecmsbilldelivery(Corecmsbilldelivery model)
        {
            return Context.UpdateNav(model).Include(z1 => z1.CorecmsbilldeliveryitemNav).ExecuteCommand() ? 1 : 0;
        }

        /// <summary>
        ///     发货，单个订单发货
        /// </summary>
        /// <param name="orderId">英文逗号分隔的订单号</param>
        /// <param name="logiCode">物流公司编码</param>
        /// <param name="logiNo">物流单号</param>
        /// <param name="items">发货明细</param>
        /// <param name="storeId">店铺收货地址</param>
        /// <param name="shipName">收货人姓名</param>
        /// <param name="shipMobile">收货人电话</param>
        /// <param name="shipAreaId">省市区id</param>
        /// <param name="shipAddress">收货地址</param>
        /// <param name="memo">发货描述</param>
        /// <param name="deliveryCompanyId">第三方对接物流编码</param>
        /// <returns></returns>
        public async Task<WebApiCallBack> Ship(string orderId, string logiCode, string logiNo, Dictionary<int, int> items, int storeId = 0, string shipName = "", string shipMobile = "", int shipAreaId = 0, string shipAddress = "", string memo = "", string deliveryCompanyId = "")
        {
            var serviceScope = _serviceProvider.CreateScope();

            //using var container = _serviceProvider.CreateScope();
            var jm = new WebApiCallBack();

            var orderService = serviceScope.ServiceProvider.GetService<ICorecmsorderService>();
            var _billDeliveryItemServices = serviceScope.ServiceProvider.GetService<ICorecmsbilldeliveryitemService>();

            //获取订单详情
            var dInfoResult = await orderService.GetOrderShipInfo(orderId);
            if (!dInfoResult.status)
            {
                return dInfoResult;
            }
            var dInfo = dInfoResult.data as AdminOrderShipOneResult;
            var orderInfo = dInfo.orderInfo;


            if (string.IsNullOrEmpty(shipName) || string.IsNullOrEmpty(shipMobile) || string.IsNullOrEmpty(shipAddress) || shipAreaId == 0)
            {
                jm.msg = "收货地址信息不全";
                jm.otherData = new
                {
                    shipName,
                    shipMobile,
                    shipAddress,
                    shipAreaId
                };
                return jm;
            }
            var billDelivery = new Corecmsbilldelivery();
            billDelivery.OrderId = string.Join(",", orderId);
            billDelivery.DeliveryId = CommonHelper.GetSerialNumberType((int)SerialNumberType.发货单编号);
            billDelivery.LogiCode = logiCode;
            billDelivery.LogiNo = logiNo;
            billDelivery.ShipAreaId = shipAreaId;
            billDelivery.ShipAddress = shipAddress;
            billDelivery.ShipName = shipName;
            billDelivery.ShipMobile = shipMobile;
            billDelivery.Status = (int)BillDeliveryStatus.Already;
            billDelivery.Memo = memo;
            billDelivery.CreateTime = DateTime.Now;
            billDelivery.ThirdPartylogiCode = "OTHERS";
            billDelivery.StoreId = storeId;
            //设置发货明细
            var bdRel = new List<Corecmsbilldeliveryitem>();

            //校验发货内容
            var tNum = 0;
            foreach (var item in items)
            {
                var orderItem = dInfo.items.Find(p => p.ProductId == item.Key);
                if (orderItem == null)
                {
                    //发货的商品不在发货明细里，肯定有问题
                    jm.msg = "未知错误";//GlobalErrorCodeVars.Code10000;
                    return jm;
                }
                //判断总发货数量
                tNum = tNum + item.Value;

                //构建发货单明细
                var bdItem = new Corecmsbilldeliveryitem();
                bdItem.DeliveryId = billDelivery.DeliveryId;
                bdItem.OrderId = orderItem.OrderId;
                bdItem.ProductId = orderItem.ProductId;
                bdItem.GoodsId = orderItem.GoodsId;
                bdItem.Bn = orderItem.Bn;
                bdItem.Sn = orderItem.Sn;
                bdItem.Weight = orderItem.Weight;
                bdItem.Name = orderItem.Name;
                bdItem.Addon = !string.IsNullOrEmpty(orderItem.Addon) ? orderItem.Addon : "";
                bdItem.Nums = orderItem.Nums;
                bdRel.Add(bdItem);
            }
            if (tNum < 1)
            {
                jm.msg = "请至少发生一件商品!";
                return jm;
            }
            //事务处理开始


            //插入发货单主体表
            await InsertAsync(billDelivery);

            //插入发货单明细表
            await _billDeliveryItemServices.InsertRangeAsync(bdRel);

            //订单更新发货状态，发送各种消息
            //await OrderShip(orderInfo, items, billDelivery, storeId);
            var res = await orderService.EditShipStatus(orderInfo.OrderId, null);
            var _orderLogServices = serviceScope.ServiceProvider.GetService<ICorecmsorderlogService>();

            if (res.status == true)
            {
                //添加操作日志
                var log = new Corecmsorderlog();
                log.OrderId = orderInfo.OrderId;
                log.UserId = orderInfo.UserId;
                log.Type = (int)OrderLogTypes.LOG_TYPE_SHIP;
                log.Msg = "订单发货操作，发货单号：" + billDelivery.DeliveryId;
                log.Data = JsonConvert.SerializeObject(billDelivery);
                log.CreateTime = DateTime.Now;
                await _orderLogServices.InsertAsync(log);


            }
            jm.status = true;
            jm.msg = "发货成功";

            return jm;
        }

        /// <summary>
        /// 给订单发货
        /// </summary>
        /// <param name="orderInfo">订单信息</param>
        /// <param name="items">总的发货包裹内容</param>
        /// <param name="deliveryInfo">发货单信息</param>
        /// <param name="storeId">门店自提还是普通订单，0是普通订单，其他是门店自提</param>
        private async Task<bool> OrderShip(Corecmsorder orderInfo, Dictionary<int, int> items, Corecmsbilldelivery deliveryInfo, int storeId = 0)
        {
            var serviceScope = _serviceProvider.CreateScope();
            var orderService = serviceScope.ServiceProvider.GetService<ICorecmsorderService>();
            var _orderLogServices = serviceScope.ServiceProvider.GetService<ICorecmsorderlogService>();

            var res = await orderService.EditShipStatus(orderInfo.OrderId, null);

            if (res.status == true)
            {
                //添加操作日志
                var log = new Corecmsorderlog();
                log.OrderId = orderInfo.OrderId;
                log.UserId = orderInfo.UserId;
                log.Type = (int)OrderLogTypes.LOG_TYPE_SHIP;
                log.Msg = "订单发货操作，发货单号：" + deliveryInfo.DeliveryId;
                log.Data = JsonConvert.SerializeObject(deliveryInfo);
                log.CreateTime = DateTime.Now;
                await _orderLogServices.InsertAsync(log);


            }
            return true;
        }



        /// <summary>
        /// 查询导出表达式
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        private static Expressionable<Corecmsbilldelivery> QueryExp(CorecmsbilldeliveryQueryDto parm)
        {
            var predicate = Expressionable.Create<Corecmsbilldelivery>();

            return predicate;
        }
    }
}